﻿Imports TBCC.UserManage
Public Class MainForm


    Sub New()
        SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        SetStyle(ControlStyles.UserPaint, True)
        SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Private Shared _pi As ProjectItem = Nothing


    Private _masterNetID As Byte = 255
    Public Property MasterNetID() As Byte
        Get
            Return _masterNetID
        End Get
        Set(ByVal value As Byte)
            _masterNetID = value
        End Set
    End Property


    Public Shared ReadOnly Property pi() As ProjectItem
        Get
            Return _pi
        End Get
    End Property


    ''' <summary>
    ''' 刷新当前工程的信息
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub RefeshCurrentProjectInfo()
        If _pi IsNot Nothing Then
            _pi = ProjectService.RefreshCurProjectList(_pi.ProjectID)
        End If
    End Sub

    Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.Text = ProjectMainWindowTitile

        Me.Refresh()

        Me.WindowState = FormWindowState.Minimized
        Me.MinimumSize = My.Computer.Screen.WorkingArea.Size
        InitBackgroundUpdate()
        InitFDAPUpdate()
        InitHisFDAPUpdate()
        InitServerUpdate()
        InitlLEDUpdate()
        InitsLEDUpdate()

        '-----------------2008-11-20-----------------
        InitClientSocket()
        '--------------Add by ZhangTeng--------------
        ' LoadProjects()
        'If My.User.CurrentPrincipal.IsInRole(RoleClass.GetRolename(RoleType.Admin)) = True Then ' 切换到Admin用户
        'PanelClient.BackgroundImage = My.Resources.Mainformbackground
        ' Else
        LoadProjects()
        ' End If

        Logger.Write(User.Instance.uID, User.Instance.uName, "登陆仓储制冷系统", tbccLogOperateType.Login)

        Init()


        


    End Sub


    Private Sub Init()
        Me.ssLogintime.Text = Now.ToString("yyyy-MM-dd HH:mm:ss")
        Me.ssUserName.Text = ""
        Me.ssTip.Text = "尚未连接"

        RefUploadTimeTick = TimerHelper.instance.GetTickCount()
    End Sub

    Private ss As ShowSelect
    Public Sub RegShowMethod(ByVal method As ShowSelect)
        ss = method
    End Sub

    Private Sub LoadProjects()
        Dim isfind As Boolean = False

        tsbProjects.DropDownItems.Clear()

        Dim il As IList(Of ProjectItem)
        il = ProjectService.GetProjectList()

        If il IsNot Nothing Then
            For Each pi As ProjectItem In il
                Dim mnu As New ToolStripMenuItem()
                mnu.Text = pi.ProjectName
                mnu.Tag = pi ' pi.ProjectID
                AddHandler mnu.Click, AddressOf mnuProject_Click
                Me.tsbProjects.DropDownItems.Add(mnu)
            Next
        End If
        If tsbProjects.DropDownItems.Count > 0 Then
            If _pi IsNot Nothing Then ' 之前已经选择工程
                For i As Integer = 0 To tsbProjects.DropDownItems.Count - 1
                    If CType(tsbProjects.DropDownItems(i).Tag, ProjectItem).ProjectID = _pi.ProjectID Then
                        tsbProjects.DropDownItems(i).PerformClick()    '默认选择已选择的工程
                        isfind = True
                    End If
                Next
            End If

            PanelClient.BackgroundImage = Nothing
            If isfind = False Then
                tsbProjects.DropDownItems(0).PerformClick()    '默认选择第一个工程
            End If
            'PanelClient.BackgroundImage = My.Resources.Mainformbackground
            'tsbProjects.Text = "选择工程"
            'TBCC.Data.BackupRestore.ConfigurationManager.ProjectID = _pi.ProjectID
            'TBCC.Data.BackupRestore.ConfigurationManager.SetMySqlConnectionString(SqlHelper.GetDBConn)
            'TBCC.Data.BackupRestore.Schedule.GetInstance().Start()
            ' g_WebServiceDataUpload = IIf(KeyValuePairClass.GetValue1("WebServiceDataUpload").Equals("1"), True, False)
            'If g_WebServiceDataUpload Then
            '    '启动webservice方法
            '    TBCC.CCRP.MonitorServer.MonitorServiceHost.Start()

            'Else
            '    '停止webservice方法
            '    TBCC.CCRP.MonitorServer.MonitorServiceHost.Stop()

            'End If
        Else
            tsbProjects.Text = "创建工程"
            PanelClient.BackgroundImage = My.Resources.Mainformbackground
            Program.CheckUserRight(Me, False, _NowStatus)
        End If

        refreshStatus()

    End Sub

    Public IsClicked As Boolean = False

    Private Sub mnuProject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If _pi IsNot Nothing Then '不是第一次打开工程
            If CType(CType(sender, ToolStripMenuItem).Tag, ProjectItem).ProjectID <> _pi.ProjectID Then '在已经打开工程的基础上再次打开其他工程
                If g_offline = False Then '前工程已连接
                    msg.Show("在切换新工程前请先挂断已连接的工程")
                    Exit Sub
                Else '前工程未连接
                    SwitchProject()
                End If
            Else  '打开相同工程
                If IsClicked Then
                    Exit Sub
                End If
            End If
        End If

        _pi = CType(CType(sender, ToolStripMenuItem).Tag, ProjectItem)
        '*************************************************************************
        '2009年06月10日 李吉鹏 增加
        '*************************************************************************

        g_BackgroundUploadHistoryData_Com = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadHistoryData_Com").Equals("1"), True, False)
        g_BackgroundUploadAlarm_Com = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadAlarm_Com").Equals("1"), True, False)
        g_BackgroundUploadDiData_Com = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "g_BackgroundUploadDiData_Com").Equals("1"), True, False)

        g_BackgroundUploadHistoryData_Tel = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadHistoryData_Tel").Equals("1"), True, False)
        g_BackgroundUploadAlarm_Tel = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadAlarm_Tel").Equals("1"), True, False)

        g_BackgroundUploadDiData_Tel = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "g_BackgroundUploadDiData_Tel").Equals("1"), True, False)
        g_BackgroundUploadHistoryData_Tcp = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadHistoryData_Tcp").Equals("1"), True, False)
        g_BackgroundUploadAlarm_Tcp = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadAlarm_Tcp").Equals("1"), True, False)

        g_BackgroundUploadDiData_Tcp = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "g_BackgroundUploadDiData_Tcp").Equals("1"), True, False)
        Program.CheckUserRight(Me, Not g_offline, _NowStatus)
        SetSwitchButtonVisible()
        '********************************************************************************************
        OpenProject()

    End Sub

    ''' <summary>
    ''' 从当前工程切换到其他工程
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SwitchProject()

        CloseAllForms()

        Me.tsbProjects.Text = ""
        'Me.ssCurrentForm.Text = ""

    End Sub

    ''' <summary>
    ''' 关闭当前选择的工程
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CloseProject()

        CloseAllForms()
        _pi = Nothing

        If tsbProjects.DropDownItems.Count > 0 Then
            tsbProjects.DropDownItems(0).PerformClick()    '默认选择第一个工程
            'PanelClient.BackgroundImage = Nothing
            tsbProjects.Text = "选择工程"
        Else
            tsbProjects.Text = "创建工程"
            'PanelClient.BackgroundImage = My.Resources.Mainformbackground
        End If
        PanelClient.BackgroundImage = My.Resources.Mainformbackground

        'Me.ssCurrentForm.Text = ""

    End Sub



#Region "打开工程"

    ''' <summary>
    ''' 打开新的工程
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub OpenProject()

        'If ProjectExists() = False Then
        '    Exit Sub
        'End If

        g_AlarmSoundFile = KeyValuePairClass.GetValue(pi.ProjectID, "AlarmSoundFile")


        Me.tsbProjects.Text = " " & _pi.ProjectName & " "

        'Me.mnuMain.PerformClick()

        refreshProjectForm()
    End Sub

    ''' <summary>
    ''' 检测选择的工程是否存在.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ProjectExists() As Boolean
        Dim bFound As Boolean = False
        For Each pi As ProjectItem In ProjectService.GetProjectList
            If _pi.ProjectID = pi.ProjectID Then
                _pi = pi
                bFound = True
                Exit For
            End If
        Next

        If Not bFound Then
            msg.ShowError("读取工程配置失败，请重新启动程序再试。")
            Return False
        End If

        Return True
    End Function

#End Region


    ''' <summary>
    ''' 初始化串口
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function InitCOM() As Boolean
        Dim com As String
        com = _pi.ComNumber.ToString()

        If com = "" Then
            msg.Show("请先配置串口")
            Return False
        End If

        If COMHelper.Instance.InitSerialPort(com.Replace("COM", ""), IO.Ports.Parity.Even) Then
            Return DirectConnect()
        Else
            msg.ShowError("初始化串口失败,请检查串口配置")
            Return False
        End If
    End Function

    ''' <summary>
    ''' 设置无法连接状态
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetDisconnect()
        g_offline = True
        Me.ssTip.ForeColor = Color.Red
        Me.ssTip.Text = "连接断开"
    End Sub

    ''' <summary>
    ''' 设置连接状态
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetConnect()
        g_offline = False
        Me.ssTip.ForeColor = Color.Black
        Me.ssTip.Text = "连接建立"
    End Sub
    'ok
    ''' <summary>
    ''' 与下位机GSM口建立直连
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function DirectConnect() As Boolean
        Dim strResult As String

        For i As Integer = 0 To 2

            strResult = COMHelper.Instance.WriteCommand(UtilityClass.GetAuthCodeByte(_pi.AuthCode), 10, 10000)
            If strResult.IndexOf("AT^AUTH=OK") >= 0 Then
                Return True
            Else
                msg.ShowError("与下位机的连接鉴权失败。")
                Return False
            End If

            System.Threading.Thread.Sleep(1000)
            Application.DoEvents()
        Next

        msg.ShowError("无法建立于下位机的连接")

        Return False
    End Function

    '-----------------2008-11-20-----------------
    '--------功能：初始Socket断线处理方法--------
    Private Sub InitClientSocket()
        COMHelper.Instance.OnDisconnect = AddressOf TCP_OnDisconnect
    End Sub
    Private Sub TCP_OnDisconnect(ByVal sender As Object, ByVal e As TBCC.SocketObject.DisconnectArgs)
        If Me.InvokeRequired Then
            Me.Invoke(New MethodInvoker(AddressOf TCP_OnDisconnectMethod))
        Else
            TCP_OnDisconnectMethod()
        End If
    End Sub
    Private Sub TCP_OnDisconnectMethod()
        'System.IO.File.AppendAllText("./ConnectInfo.Log", _
        '                                    String.Format("{0} =====> 连接类型:{1}, {2}" & vbCrLf, Now, MainForm.pi.connectType, "网络连接已经断开"), _
        '                                    System.Text.Encoding.UTF8)
        'mnuDisconnect.PerformClick()
        ''mnuReConnect.PerformClick()
        'Connect(True)
        ''msg.ShowError("网络连接已经断开")
        TCP_Connect()
    End Sub
    '-------------- 2009-03-16 ---------------
    Dim TCP_isConnected As Boolean = False
    Dim TCP_IsConnecting As Boolean = False
    Dim TCP_IsForceClose As Boolean = False
    Dim TCP_IsCloseHandler As Boolean = False
    Dim TCP_ConnectCount As UInt32 = 0

    Private Sub TCP_Connect()
        If TCP_IsConnecting = True Then
            'TCP_IsForceClose = True
            'COMHelper.Instance.Close(True)
            'TCP_IsConnecting = False
        Else

            TCP_isConnected = False
            TCP_IsCloseHandler = False


            Dim handler As New CrossAppDomainDelegate(AddressOf _TCP_Connect)
            handler.BeginInvoke(New System.AsyncCallback(AddressOf TCP_Connect_Callback), Nothing)

        End If
    End Sub

    Private Sub _TCP_Connect()
        If TCP_IsConnecting = False Then
            TCP_IsConnecting = True

            Do While TCP_IsCloseHandler = False AndAlso TCP_isConnected = False
                TCP_ConnectCount += 1
                SetStatusBar(False, Color.Red, String.Format("正在重连({0})", TCP_ConnectCount))

                SetSwitchButtonVisible()
                'Me.tsbLink.Text = "连接"
                'Me.tsbLink.Image = TBCC.AlarmSystem.My.Resources.连结
                g_busy = True
                'Try
                '    COMHelper.Instance.Close()
                'Catch ex As Exception
                '    Debug.WriteLine(ex.Message)
                'End Try



                Logger.Write(User.Instance.uID, User.Instance.uName, String.Format("正在重连({0})", TCP_ConnectCount), tbccLogOperateType.Callback)


                TCP_isConnected = COMHelper.Instance.InitSocket(_pi.IPAddress, _pi.IPPort)

                ' System.Threading.Thread.Sleep(10000)

                If TCP_isConnected = True Then
                    TCP_isConnected = False

                    Dim strResult As String
                    strResult = COMHelper.Instance.WriteCommand(UtilityClass.GetAuthCodeByte(_pi.AuthCode), 10, 10000)
                    If strResult.IndexOf("AT^AUTH=OK") >= 0 Then
                        TCP_isConnected = True

                        g_busy = False
                        ' TCP_IsConnecting = True
                        '_isAuthFail = False
                    Else
                        '_isAuthFail = True

                        TCP_IsConnecting = True
                    End If
                Else
                    System.Threading.Thread.Sleep(10000)

                End If
            Loop

            TCP_IsConnecting = False
        End If
    End Sub

    Private Sub TCP_Connect_Callback(ByVal ar As System.IAsyncResult)
        If TCP_IsConnecting = False Then
            If Me.InvokeRequired = True Then
                Me.Invoke(New CrossAppDomainDelegate(AddressOf _TCP_Connect_Callback), Nothing)
            Else
                _TCP_Connect_Callback()
            End If
        End If
    End Sub
    Private Sub _TCP_Connect_Callback()
        TCP_ConnectCount = 0

        If TCP_isConnected = True Then
            SetStatusBar(True, Color.Black, "连接建立")

            Logger.Write(User.Instance.uID, User.Instance.uName, "重连成功", tbccLogOperateType.Callback)

            Program.CheckUserRight(Me, Not g_offline, _NowStatus)
            SetSwitchButtonVisible()
            Me.tsbLink.Text = "断开"
            Me.tsbLink.Image = TBCC.AlarmSystem.My.Resources.断开

            'RunBackgroundUpdate()
        End If
    End Sub

    Private Sub SetStatusBar(ByVal online As Boolean, ByVal statusColor As Color, ByVal statusText As String)
        Dim obj As Object = New Object() {online, statusColor, statusText}
        If Me.InvokeRequired = True Then
            Me.Invoke(New Action(Of Object)(AddressOf _SetStatusBar), obj)
        Else
            _SetStatusBar(obj)
        End If
    End Sub
    Private Sub _SetStatusBar(ByVal obj As Object)
        g_offline = Not obj(0)
        Me.ssTip.ForeColor = obj(1)
        Me.ssTip.Text = obj(2)
    End Sub
    '--------------Add by ZhangTeng--------------



    'ok
    Private Sub InitBackgroundUpdate()

        '关联历史报警上传完成事件与对应的处理函数
        AddHandler BackgroundAlarmData.Instance.AlarmUploadFinishedEvent, AddressOf BeginHistoryData

        '关联历史数据上传完成事件与对应的处理函数
        AddHandler BackgroundHistorydata.Instance.HistoryDataUploadFinishedEvent, AddressOf BeginHistoryDiData

        AddHandler BackgroundDiHdData.Instance.DiDataUploadFinishedEvent, AddressOf BeginHistoryAlarmData

    End Sub
    'ok
    ''' <summary>
    ''' 允许后台上传
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub RunBackgroundUpdate()
        Try
            '**********************************************************************************************
            '2009年06月10日 李吉鹏 修改
            '**********************************************************************************************
            Select Case _pi.connectType
                Case 0 '拨号
                    If g_BackgroundUploadAlarm_Tel Then

                        Timer_HistAlarmbackground.Start() '启动历史报警数据后台读取过程
                    ElseIf g_BackgroundUploadHistoryData_Tel Then

                        Timer_HistDatabackground.Start() '启动历史数据后台读取过程

                    ElseIf g_BackgroundUploadDiData_Tel Then
                        Timer_HistDibackground.Start()
                    End If

                Case 1 '直连
                    If g_BackgroundUploadAlarm_Com Then

                        Timer_HistAlarmbackground.Start() '启动历史报警数据后台读取过程

                    ElseIf g_BackgroundUploadHistoryData_Com Then

                        Timer_HistDatabackground.Start() '启动历史数据后台读取过程

                    ElseIf g_BackgroundUploadDiData_Com Then
                        Timer_HistDibackground.Start()

                    End If
                Case 2 'TCP
                    If g_BackgroundUploadAlarm_Tcp Then

                        Timer_HistAlarmbackground.Start() '启动历史报警数据后台读取过程

                    ElseIf g_BackgroundUploadHistoryData_Tcp Then

                        Timer_HistDatabackground.Start() '启动历史数据后台读取过程

                    ElseIf g_BackgroundUploadDiData_Tcp Then

                        Timer_HistDibackground.Start()
                    End If
            End Select


            '************************************************************************************************
        Catch ex As Exception
            'msg.ShowWarning(ex.Message)
            Debug.WriteLine(ex.Message)
        End Try

    End Sub
    'ok
    ''' <summary>
    ''' 开始历史数据的后台上传
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub BeginHistoryData(ByVal sender As Object, ByVal e As EventArgs)
        Timer_HistDatabackground.Start()
        'BackgroundHistorydata.Instance.Start()
    End Sub
    'ok
    ''' <summary>
    ''' 开始历史报警的后台上传
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub BeginHistoryAlarmData(ByVal sender As Object, ByVal e As EventArgs)
        Timer_HistAlarmbackground.Start()
        'BackgroundAlarmData.Instance.Start()
    End Sub
    Private Sub BeginHistoryDiData(ByVal sender As Object, ByVal e As EventArgs)
        Timer_HistDibackground.Start()
        'BackgroundAlarmData.Instance.Start()
    End Sub

#Region "菜单项Click事件"

    'Private Sub mnuConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuConnect.Click
    '    Dim frm As New ConnectForm
    '    frm.ShowDialog()
    'End Sub
    'ok
    Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
        'Me.Close()
        ShowS()
    End Sub

    Private Sub ShowS()
        ss()
        Me.Hide()
    End Sub
    'ok
    Private Sub mnuTimeConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuTimeConfig.Click
#If LSC_CCAP_SWICH = "CCAP" Then
        ShowParameterForm(Of CCAPTimeSetForm)()
#Else
        ShowParameterForm(Of TimeSetForm)()
#End If



    End Sub
    'ok
    Private Sub mnuRealtimeAlarm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRealtimeAlarm.Click
        '#If LSC_CCAP_SWICH = "CCAP" Then
        '        Dim frm As FrmCcapRealAlarm = New FrmCcapRealAlarm(MainForm.pi.ProjectID)
        '        frm.ShowDialog()
        '#Else
        '        ShowParameterForm(Of RealAlarmForm)()
        '#End If
        ' ShowParameterForm(Of RealAlarmForm)()

        If _NowStatus Then
            ShowParameterForm(Of RealAlarmForm)()
        Else
            Dim frm As FrmCcapRealAlarm = New FrmCcapRealAlarm(MainForm.pi.ProjectID)
            frm.ShowDialog()
        End If


    End Sub
    'ok
    Private Sub mnuHistoryAlarm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHistoryAlarm.Click
        Dim frm As New HDAlarmForm
        frm.Owner = Me
        frm.ShowDialog()
    End Sub
    'ok
    Private Sub mnuHistoryData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHistorydata.Click
        Dim frm As New HDViewForm
        frm.Owner = Me
        frm.ShowDialog()
    End Sub
    'ok
    Private Sub mnuHistoryDataCurve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHistoryDataCurve.Click
        Dim frm As New HDCurveForm
        frm.Owner = Me
        frm.ShowDialog()
    End Sub
    'ok
    Private Sub mnuHDUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHDUpload.Click
        ShowParameterForm(Of DataUploadForm)()
    End Sub
    'ok
    Private Sub mnuHAUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHAUpload.Click, 上传历史报警ToolStripMenuItem.Click
        ShowParameterForm(Of AlarmDataUploadForm)()
    End Sub

    Private Sub mnuHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHelpfile.Click
        Dim helpFile As String
        helpFile = Application.StartupPath + "/help.chm"
        If System.IO.File.Exists(helpFile) Then
            System.Diagnostics.Process.Start(helpFile)
        Else
            '提示找不到帮助文件()
            msg.Show("找不到帮助文件 help.chm ")
        End If
    End Sub

    ''' <summary>
    ''' 关于对话框
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAbout.Click
        Dim frm As New AboutBox
        frm.ShowDialog()
    End Sub

#End Region
    'ok
    ''' <summary>
    ''' 状态栏时间更新
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If g_tt Then
            Timer1.Stop()
        End If
        Me.ssLogintime.Text = Now.ToString("  yyyy-MM-dd HH:mm:ss")
    End Sub

    'ok
    ''' <summary>
    ''' 串口配置
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>

    Private Sub mnuTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuTest.Click
        'Dim frm As New test1
        'frm.ShowDialog()
        ShowParameterForm(Of TestForm)()
    End Sub
    'ok
    ''' <summary>
    ''' 手动报警强制控制
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuHandAlarm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHandAlarm.Click
        ShowParameterForm(Of HandAlarmForm)()
    End Sub
    'ok
    Private Sub mnuAlarmSound_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim frm As New AlarmSoundForm
        frm.ShowDialog()
    End Sub
    'ok
    Private Sub mnuReConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuReConnect.Click


        Dim modType As String
        modType = readConfig("TransMode")

        Dim frm As New ConnectForm()
        Dim FDAPUploadItem As Boolean

        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then

            SetConnect()

            Program.CheckUserRight(Me, Not g_offline, _NowStatus)
            SetSwitchButtonVisible()
            Select Case MainForm.readConfig("SystemType")
                Case 0
                    RunBackgroundUpdate()

                    If MainForm.pi Is Nothing Then
                    Else
                        '如果需要启动上传数据，启动FDAP数据上传接口线程
                        FDAPUploadItem = IIf(FdapProjectKeyClass.GetValue(MainForm.pi.ProjectID, "FDAPRelDataUpload").Equals("1"), True, False)

                        If FDAPUploadItem Then

                            Timer_FDAPUpload.Start()
                            '  Timer_FDAPExDate.Start()

                        Else

                        End If
                        Timer_lLED.Start()
                        Timer_sLED.Start()


                    End If

                    'Try
                    '    '设置LED显示模式，通讯参数
                    LEDDLL.SetTransMode(modType, 3)

                    'Catch ex As Exception

                    'End Try


                Case Else
            End Select



            Logger.Write(User.Instance.uID, User.Instance.uName, "连接成功", tbccLogOperateType.Connect)

            


        Else

            SetDisconnect()

        End If
        'Me.Cursor = Cursors.WaitCursor
        'Me.Connect()
        'Me.Cursor = Cursors.Default
        If Not g_offline Then
            Me.tsbLink.Text = "断开"
            Me.tsbLink.Image = TBCC.AlarmSystem.My.Resources.断开
        End If
    End Sub
    'ok
    Private Sub mnuChangePassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuChangePassword.Click
        Dim frm As New TBCC.UserManage.ChangePasswordForm()
        frm.ShowDialog()
    End Sub

    'ok
    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        Timer2.Stop()

        Me.MenuStrip1.Enabled = False
        Me.Cursor = Cursors.WaitCursor

        If g_IsProjectDataRead Then
            Timer2.Start()
            Exit Sub
        End If


        Dim obj As Object = System.Activator.CreateInstance(_t)

        Me.MenuStrip1.Enabled = True
        Me.Cursor = Cursors.Default

        g_busy = True
        CType(obj, Form).ShowDialog()
        g_busy = False
    End Sub

    'ok
    ''' <summary>
    ''' 连接控制器
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Connect()
        Connect(False)
    End Sub
    Private Sub Connect(ByVal isRetry As Boolean)

        COMHelper.ConnectType = _pi.connectType

        Me.MenuStrip1.Cursor = Cursors.WaitCursor

        If _pi.connectType = 1 Then
            '直连 
            If InitCOM() = False Then
                SetDisconnect()
                Me.MenuStrip1.Cursor = Cursors.Default
                Exit Sub
            End If
        ElseIf _pi.connectType = 0 Then
            '拨号
            Dim frm As New DialForm("COM" & _pi.ComNumber.ToString(), _pi.Phone)
            If frm.ShowDialog <> Windows.Forms.DialogResult.OK Then
                SetDisconnect()
                Me.MenuStrip1.Cursor = Cursors.Default
                Exit Sub
            End If
        Else
            'TCP/IP
            If TCP_IsConnecting = False Then
                Dim frm As New TcpConnectForm(isRetry)
                If frm.ShowDialog() <> Windows.Forms.DialogResult.OK Then
                    SetDisconnect()
                    Me.MenuStrip1.Cursor = Cursors.Default
                    Exit Sub
                End If
            End If
        End If

        SetConnect()

        Program.CheckUserRight(Me, Not g_offline, _NowStatus)
        SetSwitchButtonVisible()
        'RunBackgroundUpdate()

        Me.MenuStrip1.Cursor = Cursors.Default

    End Sub


    'ok
    Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
        'If msg.ShowYesNo("是否要退出？") = Windows.Forms.DialogResult.Yes Then
        '    MyBase.OnClosing(e)
        '    System.Environment.Exit(0)
        'Else
        '    e.Cancel = True
        'End If
        e.Cancel = True
        ShowS()
    End Sub
    ''' <summary>
    ''' 冷库激活状态
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuActive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuActive.Click
        Me.ShowParameterForm(Of ActiveForm)()
    End Sub

    'ok
    Private Sub mnuUserManage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuUserManage.Click
        Dim frm As New TBCC.UserManage.UserManageForm()
        frm.ShowDialog()
    End Sub
    'ok
    ''' <summary>
    ''' 数据备份目录设置
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuBackup2Path_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuBackup2Path.Click
        'TBCC.Data.BackupRestore.ConfigurationManager.ProjectID = _pi.ProjectID
        'TBCC.Data.BackupRestore.ConfigurationManager.SetMySqlConnectionString(SqlHelper.GetDBConn)
        'Dim cm As TBCC.Data.BackupRestore.ConfigurationManager = New TBCC.Data.BackupRestore.ConfigurationManager()
        'Dim str As String = readConfig("mysqldir") + "/bin"
        'str = str.Replace("\", "/")
        ''msg.Show(str)
        'cm.SaveConfig(str)
        'cm.ShowSettingForm()

    End Sub
    'Private Function readConfig(ByVal strkey As String) As String

    '    Dim strreturn As String
    '    Dim appreader As Configuration.AppSettingsReader = New Configuration.AppSettingsReader()
    '    Try
    '        strreturn = appreader.GetValue(strkey, Type.GetType("System.String")).ToString()
    '    Catch ex As Exception
    '        strreturn = ex.Message.ToString()
    '    Finally
    '        appreader = Nothing
    '    End Try
    '    Return strreturn
    'End Function



    ''' <summary>
    ''' 断开连接
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDisconnect.Click

        TCP_IsCloseHandler = True

        Me.SetDisconnect()

       
        Try
            BackgroundAlarmData.Instance.StopRead()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try

        Try
            BackgroundHistorydata.Instance.StopRead()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try

        Try
            BackgroundDiHdData.Instance.StopRead()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)

        End Try



        Try
            FdapUploaddataClass.Instance.StopRead()
            Timer_FDAPUpload.Stop()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)

        End Try

        Try
            FdapHisdataClass.Instance.StopRead()
            Timer_FDAPExDate.Stop()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)

        End Try

        Try
            lLEDUploaddataClass.Instance.StopRead()
            Timer_lLED.Stop()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)

        End Try

        Try
            sLEDUploaddataClass.Instance.StopRead()
            Timer_sLED.Stop()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)

        End Try


        Try
            COMHelper.Instance.Close()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try

        '刷新工程界面数据
        mnuMain.PerformClick()

        Logger.Write(User.Instance.uID, User.Instance.uName, "断开成功", tbccLogOperateType.DisConnect)

        If g_offline Then
            Program.CheckUserRight(Me, Not g_offline, _NowStatus)
            SetSwitchButtonVisible()
            Me.tsbLink.Text = "连接"
            Me.tsbLink.Image = TBCC.AlarmSystem.My.Resources.连结
        End If
    End Sub

    'ok
    Private Sub SelfDetectMnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelfDetectMnu.Click
        ShowParameterForm(Of AlarmCheckForm)()
    End Sub

    'ok
    Private Sub selfDecRecordMnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuselfDecRecord.Click
        Dim frm As New AlarmCheckViewForm
        frm.ShowDialog()
    End Sub
    'ok
    Private Sub AlarmSoundMnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AlarmSoundMnu.Click
        Dim frm As New AlarmSoundForm
        frm.ShowDialog()
    End Sub

    'ok
    ''' <summary>
    ''' 将表单添加到PanelClient中
    ''' </summary>
    ''' <param name="frm"></param>
    ''' <remarks></remarks>
    Private Sub AddForm2Panel(ByVal frm As Form)
        '隐藏PanelClient内的其它窗体
        'For Each c As Form In Me.PanelClient.Controls
        '    c.Visible = False
        'Next

        frm.TopLevel = False
        frm.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        frm.Parent = Me.PanelClient
        frm.Dock = DockStyle.Fill
        'If (TypeOf frm Is ProjectOutlineForm) Then
        '    CType(frm, ProjectOutlineForm).Init()
        'End If
        frm.Show()
    End Sub

    'ok
    Private Sub MnuIOConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim frm As New AlarmUpDownParameterForm()
        frm.ShowDialog()
    End Sub
    Private Sub MnuIOConfig_Offline_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Dim frm As New AlarmUpDownParameterForm()
        frm.ShowDialog()
    End Sub

    Private Sub MnuIOConfig_Online_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ShowParameterForm(Of IOParameterForm)()
    End Sub
    'ok
    Private _t As Type

    ''' <summary>
    ''' 显示参数设置界面
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <remarks></remarks>
    Friend Sub ShowParameterForm(Of T As {Form, New})()
        While g_IsProjectDataRead
            _t = GetType(T)
            Me.Timer2.Start()
            Exit Sub
        End While

        '设置g_busy状态为True,停止实时数据的刷新
        g_busy = True

        Try
            Dim frm As New T()
            frm.ShowDialog()

            ''===================================
            '' 日期：2009-12-30
            '' 编辑：李大龙
            '' DESC：修改IO配置后更新主界面
            If (TypeOf frm Is IOParameterForm) Then
                '  frm.Handle
                If (CType(FromHandle(frm.Handle), IOParameterForm).Changed) Then
                    Me.RefeshCurrentProjectInfo()

                    For Each item As ToolStripMenuItem In Me.tsbProjects.DropDownItems '修改当前工程选择按钮的tag值
                        If CType(item.Tag, ProjectItem).ProjectID = _pi.ProjectID Then
                            item.Tag = _pi
                        End If
                    Next

                    refreshProjectForm()
                End If
            End If

            If (TypeOf frm Is IOParameterFormAlarm) Then
                If (CType(FromHandle(frm.Handle), IOParameterFormAlarm).Changed) Then
                    Me.RefeshCurrentProjectInfo()

                    For Each item As ToolStripMenuItem In Me.tsbProjects.DropDownItems '修改当前工程选择按钮的tag值
                        If CType(item.Tag, ProjectItem).ProjectID = _pi.ProjectID Then
                            item.Tag = _pi
                        End If
                    Next

                    refreshProjectForm()
                End If
            End If

            If (TypeOf frm Is ccapIOParameterForm) Then
                If (CType(FromHandle(frm.Handle), ccapIOParameterForm).Changed) Then

                    RefreshCcapForm()

                End If

            End If
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try

        '参数设置界面关闭后,设置g_busy状态为False,开始实时数据的刷新
        g_busy = False
    End Sub

    'ok
    Private Sub MnuSwitchUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuSwitchUser.Click
        Dim frm As New TBCC.UserManage.LoginForm
        If g_offline = False Then '当前连接已建立
            msg.Show("切换前请挂断当前连接")
            Exit Sub
        End If

        If frm.ShowDialog = Windows.Forms.DialogResult.OK Then
            If My.User.CurrentPrincipal.IsInRole(RoleClass.GetRolename(RoleType.Admin)) = True Then ' 切换到Admin用户
                CloseProject()
                PanelClient.BackgroundImage = My.Resources.Mainformbackground
            End If
            Program.CheckUserRight(Me, Not g_offline, _NowStatus)
            SetSwitchButtonVisible()
            refreshStatus()
        End If
    End Sub

    Public Sub SwitchUser()
        If Not g_offline Then
            Me.tsbLink.PerformClick()
        End If
        If My.User.CurrentPrincipal.IsInRole(RoleClass.GetRolename(RoleType.Admin)) = True Then ' 切换到Admin用户
            CloseProject()
            PanelClient.BackgroundImage = My.Resources.Mainformbackground
        End If
        refreshProjectForm()
        Program.CheckUserRight(Me, Not g_offline, _NowStatus)
        SetSwitchButtonVisible()
        refreshStatus()
    End Sub

    'ok
    ''' <summary>
    ''' 关闭所有MDI子窗体
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CloseAllForms()

        For Each frm As Form In Me.PanelClient.Controls
            If frm.GetType Is GetType(ProjectOutlineForm) Then
                frm.Close()
            End If
        Next
        FormTable.Clear()
        SystemInfo = 0
        Me.PanelClient.Controls.Clear()
    End Sub

    Private Sub refreshStatus()
        'Me.ssTip.Text = "就绪"
        'Me.ssCurrentForm.Text = ""
        Me.ssLogintime.Text = Now.ToString("yyyy-MM-dd HH:mm:ss")
        Me.ssUserName.Text = String.Format("当前用户：{0}", TBCC.UserManage.User.Instance.uName)
    End Sub

    Private Sub mnuprjsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuprjsave.Click

        Dim pid_str As String
        pid_str = Trim(pi.ProjectID).Replace("-", "_")

        RefeshCurrentProjectInfo() '刷新当前工程参数

        Dim frm As New SaveFileDialog()
        frm.Filter = "工程配置文件(*.tbl)|*.tbl"
        frm.FileName = ""
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim f As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            Dim s As New IO.FileStream(frm.FileName, IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.None)
            Try
                f.Serialize(s, pi)
            Catch ex As Exception
                msg.ShowError(ex.Message)
                Exit Sub
            Finally
                s.Close()
            End Try
            msg.Show("工程导出成功")
        End If
    End Sub

    Private Sub mnuprjload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuprjload.Click

        Dim dti As DevTypeItem = Nothing
        Dim m_pi As ProjectItem

        'If pi IsNot Nothing Then '在工程已选择的情况下无法导入工程信息
        '    msg.Show("当前无法导入工程配置信息,请重新启动程序")
        '    Exit Sub
        'End If

        If msg.ShowYesNo("导入操作将覆盖已有相同工程的所有配置信息及清除掉该工程所以数据,是否继续?") = Windows.Forms.DialogResult.No Then
            Exit Sub
        End If

        Dim frm As New OpenFileDialog()
        frm.Filter = "工程配置文件(*.tbl)|*.tbl"
        frm.FileName = ""
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim f As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            Dim s As New IO.FileStream(frm.FileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
            Try
                '  Dim a As Object = f.Deserialize(s)

                m_pi = CType(f.Deserialize(s), ProjectItem)
                If m_pi.VersionNo = "" Then  '修改所有工程ID为4位
                    Dim frmPid As New ChangePidFrom
                    'frmPid.ShowDialog()
                    If frmPid.ShowDialog() = Windows.Forms.DialogResult.OK Then
                        m_pi.ProjectID = frmPid.proIDtext.Text.Trim
                    Else
                        Exit Sub

                    End If
                End If
                If True = ProjectService.UpdatePrjDataToDb(m_pi, ProjectService.DevTypeMaxNetid(m_pi.ProjectID, 1), ProjectService.DevTypeMaxNetid(m_pi.ProjectID, 16)) Then '将工程信息更新到数据库
                    LoadProjects()    '更新工具栏工程列表
                    '更新加载仓储工程字段值
                    KeyValuePairClass.SetValue1("loadstorageproject", 1)

                    msg.Show("工程导入成功")
                Else
                    msg.Show("工程导入失败")
                End If
            Catch ex As Exception
                msg.ShowError(ex.Message)
                Exit Sub
            Finally
                s.Close()
            End Try

        End If

    End Sub
    'ok
    Private Sub mnunetaddr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnunetaddr.Click
        ShowParameterForm(Of NetAddressConfigForm)()
    End Sub
    'ok
    Private Sub mnunetstruct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnunetstruct.Click


    End Sub
    'ok
    'Private Sub submenu_zerorevise_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    ShowParameterForm(Of AIZeroReviseForm)()
    'End Sub
    'ok
    'Private Sub submenu_devrevise_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    ShowParameterForm(Of AIDeviationReviseForm)()
    'End Sub
    'ok
    'Private Sub submenu_AIread_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Me.ShowParameterForm(Of AIZeroReadForm)()
    'End Sub
    'ok
    Private Sub mnuPhoneConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPhoneConfig.Click
        ShowParameterForm(Of PhoneNumberForm)()
    End Sub
    'ok
    Private Sub submnu_connectinfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submnu_connectinfo.Click
        'If g_offline = False Then '当前工程已经连接时不允许配置工程信息
        '    msg.Show("配置工程连接信息前请先断开当前工程连接")
        '    Exit Sub
        'End If

        Dim frm As New ProjectManageForm()
        frm.ShowDialog()

        If frm.Update_Flag = True Then '参数发生修改
            LoadProjects()
            Me.RefeshCurrentProjectInfo() '刷新到当前工程信息变量中

            If _pi Is Nothing Then  '刷新
                Me.CloseAllForms()
                Program.CheckUserRight(Me, False, _NowStatus) '修改当前菜单状态
                SetSwitchButtonVisible()
            Else
                For Each item As ToolStripMenuItem In Me.tsbProjects.DropDownItems
                    If CType(item.Tag, ProjectItem).ProjectID = _pi.ProjectID Then
                        Me.tsbProjects.Text = _pi.ProjectName
                    End If
                Next
            End If
        End If
    End Sub
    'ok
    Private Sub submenu_devpara_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submenu_devpara.Click
        '#If LSC_CCAP_SWICH = "CCAP" Then
        '        Dim frm As New CcapdevTypeForm
        '        frm.ShowDialog()
        '#Else
        Dim frm As New ProjectTypeManageForm()
        frm.ShowDialog()

        If frm.IsModified = True Then '参数发生修改
            'Me.RefeshCurrentProjectInfo() '刷新到当前工程信息变量中
            refreshProjectForm()
        End If
        '#End If




    End Sub

    'ok
    Private Sub mnuMain_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuMain.Click
        'If _NowStatus Then
        refreshProjectForm()

        ' End If

    End Sub

    'ok
    Private Sub mnuRealDataCurve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRealDataCurve.Click
        'Dim frm As New RealtimeCurveForm()
        'frm.ShowDialog()
        msg.Show("暂未完成")
    End Sub


    Private Sub submenu_prjimage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submenu_prjimage.Click
        Dim frm As New ProjectImageManageForm(_pi)
        frm.ShowDialog()

        If frm.UpdateFlag Then '图层发生修改            
            Me.RefeshCurrentProjectInfo()

            For Each item As ToolStripMenuItem In Me.tsbProjects.DropDownItems '修改当前工程选择按钮的tag值
                If CType(item.Tag, ProjectItem).ProjectID = _pi.ProjectID Then
                    item.Tag = _pi
                End If
            Next

            refreshProjectForm()
        End If
    End Sub

    Private Sub tsbProjects_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbProjects.Click
        If tsbProjects.Text = "创建工程" Then
            If MenuItemProjectConfig.Visible = True Then
                submnu_connectinfo.PerformClick()
            Else
                msg.Show("当前用户无创建工程权限")
            End If
        End If
    End Sub

    Private Sub Timer_HistAlarmbackground_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_HistAlarmbackground.Tick
        Timer_HistAlarmbackground.Stop()
        BackgroundAlarmData.Instance.Start()
    End Sub

    Private Sub Timer_HistDatabackground_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_HistDatabackground.Tick
        Timer_HistDatabackground.Stop()
        BackgroundHistorydata.Instance.Start()
    End Sub

    Public Sub refreshProjectForm()
        Dim gp As System.Security.Principal.GenericPrincipal
        gp = My.User.CurrentPrincipal

        CloseAllForms()
        '#If LSC_CCAP_SWICH = "CCAP" Then
        '   AddForm2Panel(New FrmCcapRealData(MainForm.pi.ProjectID))
        '#Else
        ''===========================
        '' date:2009-12-29
        '' author:lidalong
        '' cause: BUG00002 减少界面闪烁问题
        If MainForm.pi Is Nothing Then
            Exit Sub
        End If
        Dim frmAlarm As ProjectOutlineForm
        frmAlarm = New ProjectOutlineForm()
        Dim frmCcap As New FrmCcapRealData(MainForm.pi.ProjectID)
        If MainForm.pi.DevTypeGroupList.Count > 0 And MainForm.pi.CcappDevList.Count > 0 Then '混合
            If Not FormTable.ContainsKey("ALARM") Then
                FormTable.Add("ALARM", frmAlarm)
            End If
            If Not FormTable.ContainsKey("CCAP") Then
                FormTable.Add("CCAP", frmCcap)
            End If
            SystemInfo = 3
        ElseIf MainForm.pi.DevTypeGroupList.Count > 0 Then '单仓储
            If Not FormTable.ContainsKey("ALARM") Then
                FormTable.Add("ALARM", frmAlarm)
                If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
                    FormTable.Add("CCAP", frmCcap)
                End If
            End If
            SystemInfo = 1
        ElseIf MainForm.pi.CcappDevList.Count > 0 Then '单制冷
            If Not FormTable.ContainsKey("CCAP") Then
                FormTable.Add("CCAP", frmCcap)
                If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
                    FormTable.Add("ALARM", frmAlarm)
                End If
            End If
            SystemInfo = 2
        Else
            ' Exit Sub
            SystemInfo = 0
            If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
                FormTable.Add("ALARM", frmAlarm)
                FormTable.Add("CCAP", frmCcap)
                AddForm2Panel(frmAlarm)
                AddForm2Panel(FormTable("CCAP"))
                tsbSwitch.Visible = True
            Else
                tsbSwitch.Visible = False
            End If
        End If

        'msg.Show(Me.pi.ProjectID)
        If SystemInfo = 1 Or SystemInfo = 3 Then
            AddForm2Panel(FormTable("ALARM"))
            If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
                AddForm2Panel(FormTable("CCAP"))
            End If
        End If
        If SystemInfo = 2 Or SystemInfo = 3 Then
            AddForm2Panel(FormTable("CCAP"))
            If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
                AddForm2Panel(FormTable("ALARM"))
            End If
        End If



        Select Case SystemInfo
            Case 1
                Me._NowStatus = True
                'setAlarmVisable(True)
                Program.CheckUserRight(Me, Not g_offline, _NowStatus)
                ShowFormByKey("alarm")
                If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
                    tsbSwitch.Visible = True
                Else
                    tsbSwitch.Visible = False
                End If
                Me.tsbSwitch.Text = "切换制冷"
            Case 2
                Me._NowStatus = False
                'setAlarmVisable(False)
                Program.CheckUserRight(Me, Not g_offline, _NowStatus)
                ShowFormByKey("ccap")
                If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
                    tsbSwitch.Visible = True
                Else
                    tsbSwitch.Visible = False
                End If
                Me.tsbSwitch.Text = "切换仓储"
            Case 3
                'Me._NowStatus = True
                ''setAlarmVisable(True)
                'Program.CheckUserRight(Me, Not g_offline, _NowStatus)
                'SetSwitchButtonVisible()
                'ShowFormByKey("alarm")
                'tsbSwitch.Visible = True


                Program.CheckUserRight(Me, Not g_offline, _NowStatus)
                SetSwitchButtonVisible()


                If Me._NowStatus Then
                    ShowFormByKey("alarm")
                    Me.tsbSwitch.Text = "切换制冷"
                Else
                    ShowFormByKey("ccap")
                    Me.tsbSwitch.Text = "切换仓储"


                End If

                tsbSwitch.Visible = True

                '  Me.tsbSwitch.Text = "制冷系统"


        End Select
        frmAlarm.Loaded = True
        '#End If


    End Sub

    Private Sub MnuItemUniformitySetting_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuItemUniformitySetting.Click
        Dim frm As New UniformityConfigForm
        frm.ShowDialog()
    End Sub

    Private Const _ufFileKey As String = "UniformityPath"
    Private Const _ufTimeKey As String = "UniformityTime"

    Private Sub TimerUniformityBackup_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerUniformityBackup.Tick
        Me.TimerUniformityBackup.Stop()

        If g_offline = True Then
            Me.TimerUniformityBackup.Start()
            Exit Sub
        End If

        Dim path As String
        path = KeyValuePairClass.GetValue(pi.ProjectID, _ufFileKey)
        If path = "" OrElse Not System.IO.Directory.Exists(path) Then
            Me.TimerUniformityBackup.Start()
            Exit Sub
        End If

        Dim strTime As String
        strTime = KeyValuePairClass.GetValue(pi.ProjectID, _ufTimeKey)
        strTime = strTime.Trim()
        If strTime = "" Then
            strTime = "00:00:00"
            Me.TimerUniformityBackup.Start()
            Exit Sub
        End If

        Dim curTime As DateTime
        curTime = Now

        Dim backupTime As DateTime
        backupTime = curTime.ToString("yyyy-MM-dd ") & strTime

        If DateDiff(DateInterval.Minute, curTime, backupTime) = 0 Then

            Try
                capture_all(path)
            Catch
                msg.ShowError("均匀度数据保存失败")
            Finally
                For i As Integer = 1 To 1200 '等待2分钟后重新启动定时器,防止重复备份
                    System.Threading.Thread.Sleep(100)
                    Application.DoEvents()
                Next
            End Try
        End If

        Me.TimerUniformityBackup.Start()
    End Sub

    ' 获取当前工程均匀度数据
    Public Function capture_all(ByVal path As String) As Boolean
        Dim g As Graphics
        Dim PicRec As Rectangle
        Dim m_frm As ProjectOutlineForm
        Dim ret As Boolean = False
        Dim bmpfilename As String
        Dim mBmp As Bitmap
        Dim drawstr As String = String.Empty
        Dim mColor As System.Drawing.Color
        Dim mBrush As Brush
        Dim findData As Boolean

        While g_IsProjectDataRead = True  '工程数据正在读取中暂停保存
            System.Threading.Thread.Sleep(50)
        End While

        g_IsSaveProjectImg = True '开始保存工程图信息

        Try

            ' PicRec = New Rectangle(Me.PanelClient.Location, Me.PanelClient.Size) '根据panelclient组件计算保存的图像的位置和大小

            For Each frm As Form In Me.PanelClient.Controls   '但前工程窗体
                If frm.GetType Is GetType(ProjectOutlineForm) Then
                    m_frm = CType(frm, ProjectOutlineForm)
                    m_frm.Cursor = Cursors.WaitCursor

                    PicRec = m_frm.TabControlImages.SelectedTab.ClientRectangle

                    For Each pii As ProjectImageItem In pi.imageList '该工程每一背景图层
                        '记录当前图层的保存路径和名称
                        bmpfilename = path & "/" & String.Format("{0}仓储环境均匀度_{1}_{2}.ufa", pi.ProjectName, pii.imageName, Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace(":", ".")
                        If Not System.IO.File.Exists(pii.imagePath) Then

                        Else : pii.imagePath = pii.imageoppPath
                            If Not System.IO.File.Exists(pii.imagePath) Then

                                Continue For
                            End If
                        End If

                        mBmp = System.Drawing.Bitmap.FromFile(pii.imagePath)

                        ''===================================
                        '' date:2009-12-29
                        '' author :lidalong
                        '' cause: BUG00018

                        g = Graphics.FromImage(mBmp.GetThumbnailImage(PicRec.Width, PicRec.Height, Nothing, IntPtr.Zero))

                        For Each ImgItem As ImgControlItem In pii.ImgControlItemGroupList  '对每一背景图层中的每一图元信息
                            findData = False
                            For Each podi As ProjectOutlineDataItem.OutlineItem In m_frm.PodItem.outlineItemList '每个网络的数据
                                If ImgItem.Netid = podi.netID Then
                                    mColor = Color.Black
                                    If ImgItem.DataType = 1 OrElse ImgItem.DataType = 2 Then '温度或湿度数据
                                        drawstr = podi.GetAiValue(ImgItem.PortNo) & ImgItem.UnitMsg
                                    ElseIf ImgItem.DataType = 3 Then '报警数据
                                        If ImgItem.PortNo = 1 Then '冷库报警  （此处使用报警数据中不用的portno表示不同的报警类型）
                                            drawstr = podi.GetRefAlarmStatus(ImgItem.Refid, ImgItem.Netid)
                                        ElseIf ImgItem.PortNo = 2 Then '声光报警功能
                                            drawstr = podi.GetSoundAlarmStatus(ImgItem.Refid, ImgItem.Netid)
                                        ElseIf ImgItem.PortNo = 3 Then '缺项报警功能
                                            drawstr = podi.GetLostPowerStatus(ImgItem.Refid)
                                        ElseIf ImgItem.PortNo = 4 Then '库门预警功能
                                            drawstr = podi.GetDoorAlarmStatus(ImgItem.Refid)
                                        End If
                                    End If

                                    '在背景图上增加图元信息
                                    If drawstr.IndexOf("报警") = -1 Then '不是报警
                                        mBrush = New SolidBrush(Color.Black)
                                    Else
                                        mBrush = New SolidBrush(Color.Red)
                                    End If
                                    g.DrawString(ImgItem.TitleMsg & " " & drawstr, Me.Font, mBrush, (ImgItem.cLeft / 1024.0) * mBmp.Size.Width, (ImgItem.cTop / 768.0) * mBmp.Size.Height)
                                    findData = True
                                    Exit For
                                End If
                            Next

                            If findData = False Then '没有读取到数据
                                mColor = Color.Black
                                mBrush = New SolidBrush(Color.Black)
                                If ImgItem.DataType = 1 OrElse ImgItem.DataType = 2 Then '温度或湿度数据
                                    drawstr = "##.##"
                                ElseIf ImgItem.DataType = 3 Then '报警数据
                                    drawstr = "无数据"
                                End If
                                g.DrawString(ImgItem.TitleMsg & " " & drawstr, Me.Font, mBrush, (ImgItem.cLeft / 1024.0) * mBmp.Size.Width, (ImgItem.cTop / 768.0) * mBmp.Size.Height)
                            End If
                        Next
                        Try
                            mBmp.Save(bmpfilename, Drawing.Imaging.ImageFormat.Jpeg)
                            ret = True
                        Catch e As Exception
                            Exit For
                        End Try
                    Next

                    m_frm.Cursor = Cursors.Default
                End If
            Next

        Catch ex As Exception
            ret = False
        Finally
            g_IsSaveProjectImg = False '停止保存工程图信息
        End Try

        Return ret

    End Function

    Private Declare Function CreateDC Lib "gdi32.dll" Alias "CreateDCA" (ByVal lpszDriver As String, ByVal lpszDevice As String, ByVal lpszOutput As String, ByVal lpInitData As IntPtr) As IntPtr
    Private Declare Function BitBlt Lib "GDI32" (ByVal hdcDest As IntPtr, ByVal nXDest As Integer, ByVal nYDest As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hdcSrc As IntPtr, ByVal nXSrc As Integer, ByVal nYSrc As Integer, ByVal dwRop As Integer) As Boolean

    Public Function capture_projectImage(ByVal Rec As Rectangle, ByVal filename As String) As Boolean

        Try

            Dim ScreenTempHdc As IntPtr = CreateDC("DISPLAY", Nothing, Nothing, CType(Nothing, IntPtr))

            Dim ScreenGraph As Graphics = Graphics.FromHdc(ScreenTempHdc)

            '创建一个新的Graphics对象 

            Dim bmpOrigin As Bitmap = New Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, ScreenGraph)

            '根据屏幕大小创建一个相同大小的Bitmap 

            Dim OriginGraph As Graphics = Graphics.FromImage(bmpOrigin)

            Dim ScreenHdc As IntPtr = ScreenGraph.GetHdc() '获取屏幕的句柄 

            Dim bmpOriginHdc As IntPtr = OriginGraph.GetHdc() '获取位图的句柄 　　 

            BitBlt(bmpOriginHdc, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, ScreenHdc, 0, 0, 13369376) '把当前屏幕复制到位图中 

            ScreenGraph.ReleaseHdc(ScreenHdc) '释放屏幕句柄 

            OriginGraph.ReleaseHdc(bmpOriginHdc) '释放位图句柄 

            '仅将屏幕中的工程数据部分图形保存
            Dim bmpNew As New Bitmap(Rec.Width, Rec.Height, OriginGraph)
            Dim ee As Graphics = Graphics.FromImage(bmpNew)
            Dim destRect As New Rectangle(0, 0, Rec.Width, Rec.Height)
            Dim srcRect As New Rectangle(Rec.X, Rec.Y, Rec.X + Rec.Width, Rec.Y + Rec.Height)
            ee.DrawImage(bmpOrigin, destRect, srcRect, GraphicsUnit.Pixel)

            bmpNew.Save(filename, Drawing.Imaging.ImageFormat.Jpeg)

        Catch ex As Exception
            Return False
        End Try

        Return True

    End Function


    Private Sub MnuUniformityAnalysis_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuUniformityAnalysis.Click
        Dim frm As New UniformityViewForm
        frm.ShowDialog()
    End Sub

    Private Sub MnuUniformityManualSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuUniformityManualSave.Click

        Dim path As String
        path = KeyValuePairClass.GetValue(pi.ProjectID, _ufFileKey)
        If path = "" OrElse Not System.IO.Directory.Exists(path) Then
            msg.Show("请先设置保存路径")
            Exit Sub
        End If

        If msg.ShowYesNo("是否手动保存当前均匀度数据?") = Windows.Forms.DialogResult.Yes Then

            Try
                If capture_all(path) = True Then
                    msg.Show("保存均匀度数据成功")
                Else
                    msg.Show("保存均匀度数据失败")
                End If
            Catch
                msg.Show("保存均匀度数据失败")
            End Try

        End If
    End Sub

    Private Sub mnuSensorCaliDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSensorCaliDoc.Click
        Dim frm As New CalibLogViewForm
        frm.ShowDialog()
    End Sub

    Private Sub tsbMain_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbMain.Click
        'If _NowStatus Then
        mnuMain.PerformClick()

        ' End If

    End Sub

    Private Sub tsbAlarm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbAlarm.Click

        '#If LSC_CCAP_SWICH = "CCAP" Then
        '  menuCcapRealAlarm.PerformClick()
        '#Else
        '        mnuRealtimeAlarm.PerformClick()
        '#End If

        'If _NowStatus Then
        mnuRealtimeAlarm.PerformClick()
        'Else
        '    Dim frm As FrmCcapRealAlarm = New FrmCcapRealAlarm(MainForm.pi.ProjectID)
        '    frm.ShowDialog()
        'End If
    End Sub

    Private Sub tsbHistCurve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbHistCurve.Click
        mnuHistoryDataCurve.PerformClick()
    End Sub

    Private Sub tsbDataUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 上传历史数据ToolStripMenuItem.Click
        mnuHDUpload.PerformClick()
    End Sub

    Private Sub mnuHistDataDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHistDataDoc.Click, tsbHisData.Click
        Dim frm As New HDDocViewForm
        frm.ShowDialog()
    End Sub

    Private Sub mnuHistAlarmDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHistAlarmDoc.Click, tsbHisAlarm.Click
        Dim frm As New HDDocAlarmForm
        frm.ShowDialog()
    End Sub

    Private Sub mnuSelfTestDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSelfTestDoc.Click
        Dim frm As New DocAlarmCheckViewForm
        frm.ShowDialog()
    End Sub

    Private Sub mnuDocConf_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDocConf.Click
        Dim frm As New DocViewSetForm
        frm.ShowDialog()
    End Sub


    Private Sub mnuDbClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDbClear.Click
        If g_offline = False Then
            msg.Show("数据清除前请先挂断连接")
            Exit Sub
        End If
        ShowParameterForm(Of DBClearForm)()
    End Sub

    Private Sub mnuHostAddress_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHostAddress.Click
        ShowParameterForm(Of HostAddressForm)()
    End Sub

    Private Sub mnuServerAddress_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuServerAddress.Click
        ShowParameterForm(Of ServerAddressForm)()
    End Sub

    Private Sub mnuConnectParameter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuConnectParameter.Click
        ShowParameterForm(Of NetConfigForm)()
    End Sub

    Private Sub mnuDataUploadConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDataUploadConfig.Click
        ShowParameterForm(Of DataUploadConfigForm)()
    End Sub

    'Private Sub submenu_valrevise_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    ShowParameterForm(Of AIValueReviseForm)()
    'End Sub

    Private Sub mnuBgUploadConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuBgUploadConfig.Click
        Dim frm As New BgUploadConfigForm()
        frm.ShowDialog()
    End Sub

    Private Sub submenu_zerorevise_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submenu_zerorevise.Click
        ShowParameterForm(Of AIZeroReviseForm)()
    End Sub


    Private Sub submenu_AIread_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submenu_AIread.Click
        Me.ShowParameterForm(Of AIZeroReadForm)()
    End Sub

    Private Sub submenu_devrevise_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submenu_devrevise.Click
        ShowParameterForm(Of AIDeviationReviseForm)()
    End Sub

    Private Sub submenu_valrevise_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submenu_valrevise.Click
        ShowParameterForm(Of AIValueReviseForm)()
    End Sub

    Private Sub MnuIOConfigdefine_offline_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuIOConfigdefine_offline.Click

#If LSC_WMS_SWITCH = "PREALARM" Then
        Dim frm As New IOParameterFormAlarm(False)
#Else

        Dim frm As New IOParameterForm(False)

#End If

        frm.ShowDialog()

        ''===================================
        '' 日期：2009-12-30
        '' 编辑：李大龙
        '' DESC：修改IO配置后更新主界面
        If (frm.Changed) Then
            Me.RefeshCurrentProjectInfo()

            For Each item As ToolStripMenuItem In Me.tsbProjects.DropDownItems '修改当前工程选择按钮的tag值
                If CType(item.Tag, ProjectItem).ProjectID = _pi.ProjectID Then
                    item.Tag = _pi
                End If
            Next

            refreshProjectForm()
        End If
    End Sub

    Private Sub MnuIOConfigdefine_online_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuIOConfigdefine_online.Click

#If LSC_WMS_SWITCH = "PREALARM" Then
        ShowParameterForm(Of IOParameterFormAlarm)()
#Else
        ShowParameterForm(Of IOParameterForm)()

#End If


    End Sub

    Private Sub ToolStripMenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim frm As New ProjectImageManageForm(_pi)
        frm.ShowDialog()

        If frm.UpdateFlag Then '图层发生修改            
            Me.RefeshCurrentProjectInfo()

            For Each item As ToolStripMenuItem In Me.tsbProjects.DropDownItems '修改当前工程选择按钮的tag值
                If CType(item.Tag, ProjectItem).ProjectID = _pi.ProjectID Then
                    item.Tag = _pi
                End If
            Next

            refreshProjectForm()
        End If
    End Sub

    Private Sub Modify_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Modify.Click
        Dim frm As New MainForm1
        frm.Show()
        'ShowParameterForm(Of MainForm1)()
    End Sub




    Private Sub UpLoadConMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpLoadConMenuItem.Click
        'ShowParameterForm(Of DataUploadConForm)()

    End Sub

    Private Sub ToolStripMenuItem5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AlarmpaConMenu.Click
#If LSC_WMS_SWITCH = "PREALARM" Then

        ShowParameterForm(Of AlarmUpDownParameterFormAlarm)()
#Else
       ' Dim frm As New AlarmUpDownParameterForm()
          ShowParameterForm(Of AlarmUpDownParameterForm)()
#End If

        ' frm.ShowDialog()
    End Sub

    Private Sub ToolStripMenuItem5_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UploadRecordConMenu.Click
        ShowParameterForm(Of DataUploadConForm)()
    End Sub

    Private Sub ToolStripMenuItem6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpLoadRecordSpaceMenu.Click
        ShowParameterForm(Of UpLoadRecordSetFrom)()
    End Sub

    Private Sub ToolStripMenuItem5_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuDbRevert.Click
        'Dim br As TBCC.Data.BackupRestore.Restore = New TBCC.Data.BackupRestore.Restore
        'br.DoWork(TBCC.Data.BackupRestore.Schedule.GetInstance().Setting)
    End Sub

    Private Sub TimerBackupDB_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub MenuItemParameter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItemSysCfg.Click

    End Sub

    ''' <summary>
    ''' 显示实时报警
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub menuCcapRealAlarm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuCcapRealAlarm.Click
        Dim frm As FrmCcapRealAlarm = New FrmCcapRealAlarm(MainForm.pi.ProjectID)
        frm.ShowDialog()
    End Sub

    Private Sub menuCcapRealData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuCcapRealData.Click
        Dim frm As FrmCcapRealData = New FrmCcapRealData(MainForm.pi.ProjectID)
        frm.ShowDialog()
    End Sub

    Private Sub CcapDevMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CcapDevMenuItem.Click
        Dim frm As New CcapdevTypeForm
        frm.ShowDialog()
        RefreshCcapForm()
    End Sub

    Private Sub RefreshCcapForm()
        Dim frmOld As Form = FormTable("CCAP")
        frmOld.Close()
        If FormTable.ContainsKey("CCAP") Then
            FormTable.Remove("CCAP")
        End If
        Dim frmNew As New FrmCcapRealData(MainForm.pi.ProjectID)
        FormTable.Add("CCAP", frmNew)
        AddForm2Panel(frmNew)
        ShowFormByKey("ccap")
    End Sub

    Private Sub ccapIOParameterMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ccapIOParameterMenuItem.Click
        ' Dim frm As New ccapIOParameterForm()
        'frm.ShowDialog()
        ShowParameterForm(Of ccapIOParameterForm)()



       


    End Sub

    Private Sub ccapNetNumMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ccapNetNumMenuItem.Click
        'Dim frm As New ccapNetTopologyForm
        'frm.ShowDialog()

        ShowParameterForm(Of ccapNetTopologyForm)()
    End Sub

    Private Sub MnuIOConfigdefine_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuIOConfigdefine.Click
#If LSC_CCAP_SWICH = "CCAP" Then
        ShowParameterForm(Of ccapIOParameterForm)()

#End If
    End Sub

    Private Sub CcapTimeShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CcapTimeShow.Click
        ShowParameterForm(Of CCAPTimeSetForm)()
    End Sub

    Private Sub IOToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IOToolStripMenuItem.Click
        'ShowParameterForm(Of IOdriverTypeForm)()
        ShowParameterForm(Of IOPortActiveForm)()
    End Sub

    Private Sub DevAppEx16TypeItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub DevEx16TypeItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DevEx16TypeItem.Click
        ShowParameterForm(Of DevTypeEx16ItemForm)()
    End Sub

    Private Sub DevExMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        ShowParameterForm(Of NetTopologyForm)()

    End Sub

    Private Sub GPRSMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ShowParameterForm(Of APNConfigForm)()
    End Sub


    Private Sub EthernetDevMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EthernetDevMenuItem.Click
        ShowParameterForm(Of EthernetDevForm)()
    End Sub

    Private Sub GPRSMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GPRSMenuItem.Click
        ShowParameterForm(Of APNConfigForm)()
    End Sub

    Private Sub AlarmDevMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AlarmDevMenuItem.Click
        ShowParameterForm(Of AlarmDevForm)()
    End Sub

    Public ReadOnly Property IsOffline() As Boolean
        Get
            Return g_offline
        End Get
    End Property


    ''' <summary>
    ''' 系统当前显示状态(true为仓储 false为制冷)
    ''' </summary>
    ''' <remarks></remarks>
    Private _NowStatus As Boolean = True

    Public ReadOnly Property NowStatus() As Boolean
        Get
            Return _NowStatus
        End Get
    End Property

    ''' <summary>
    ''' 系统信息(0为未配置 1仓储 2制冷 3仓储+制冷)
    ''' </summary>
    ''' <remarks></remarks>
    Private SystemInfo As Integer = 0

    Private FormTable As New Hashtable

    Private Sub tsbSwitch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbSwitch.Click

        If _NowStatus Then
            _NowStatus = False
            ' setAlarmVisable(NowStatus)
            Program.CheckUserRight(Me, Not g_offline, _NowStatus)
            Me.tsbSwitch.Text = "切换仓储"

            ShowFormByKey("ccap")
        Else
            _NowStatus = True
            ' setAlarmVisable(NowStatus)
            Program.CheckUserRight(Me, Not g_offline, _NowStatus)
            ShowFormByKey("alarm")
            Me.tsbSwitch.Text = "切换制冷"
        End If

        SetSwitchButtonVisible()

    End Sub

    Public Sub SetSwitchButtonVisible()
        Dim gp As System.Security.Principal.GenericPrincipal
        gp = My.User.CurrentPrincipal
        Select Case SystemInfo
            Case 0, 1, 2
                If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
                    Me.tsbSwitch.Visible = True
                Else
                    Me.tsbSwitch.Visible = False
                End If
            Case 3
                Me.tsbSwitch.Visible = True
        End Select
    End Sub

    Private Sub ShowFormByKey(ByVal key As String)
        For Each item As Object In FormTable.Values
            If TypeOf item Is Form Then
                Dim frm1 As Form = CType(item, Form)
                frm1.Hide()
            End If
        Next
        key = key.ToUpper()
        If Not FormTable.ContainsKey(key) Then
            ' msg.ShowError("未找到该页")
            Exit Sub
        End If
        Dim frm As Form = FormTable(key)
        frm.Show()
        frm.Refresh()
    End Sub

    Private Sub tsbReturn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbReturn.Click
        ShowS()
    End Sub

    Private Sub tsbLink_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbLink.Click
        If Me.mnuReConnect.Enabled Then
            Me.mnuReConnect.PerformClick()
        Else
            Me.mnuDisconnect.PerformClick()
        End If
    End Sub


    Private Sub tsmiCcapActive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmiCcapActive.Click
        'Dim frm As ccapIOActiveForm
        'frm.ShowDialog()
        ShowParameterForm(Of ccapIOActiveForm)()

    End Sub

    Private Sub tsmiCcapAlarmCfg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmiCcapAlarmCfg.Click
        ShowParameterForm(Of ccapIOAlarmForm)()

    End Sub

    Private Sub Timer_HistDibackground_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_HistDibackground.Tick
        Timer_HistDibackground.Stop()
        BackgroundDiHdData.Instance.Start()
    End Sub

    Private Sub DiMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DiMenuItem.Click
        menuDiUpload.PerformClick()
    End Sub

    Private Sub menuDiUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuDiUpload.Click
        ShowParameterForm(Of DiDataUploadForm)()
    End Sub

    Private Sub menuDiDataView_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuDiDataView.Click
        Dim frm As New HDDocDiForm
        frm.ShowDialog()
    End Sub

    Private Sub WebserviceToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WebserviceToolStripMenuItem.Click
        Dim frm As New WebAddForm
        frm.ShowDialog()
    End Sub

    Private Sub Webservice导出配置ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            Dim export As New TBCC.CCRP.WSCore.SensorsInitializer
            export.ExportSensors()
            msg.ShowError("导出参数成功！")

        Catch ex As Exception
            msg.ShowError("导出参数失败！")

        End Try

    End Sub

    Private Sub tsbHisSt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbHisSt.Click
        Dim frm As New HDDocDiForm
        frm.ShowDialog()
    End Sub

    Private Sub menPowerTime_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menPowerTime.Click
        ShowParameterForm(Of FrmDeviceRestartTime)()
    End Sub

    Private Sub menPowerView_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menPowerView.Click
        Dim frm As New FrmDeviceRestartView()
        frm.ShowDialog()
    End Sub


    Private Sub fdapProjectMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles fdapProjectMenuItem.Click

        Dim frm As New FdapProjectSetForm()
        frm.ShowDialog()
    End Sub

    Private Sub fdapportMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles fdapportMenuItem.Click
        Dim frm As New FdapIOportSetForm
        frm.ShowDialog()
    End Sub

    Private Sub Timer_FDAPUpload_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_FDAPUpload.Tick

        Dim FDAPUploadItem As Boolean
        Timer_FDAPUpload.Stop()

        '如果需要启动上传数据，启动FDAP数据上传接口线程
        If MainForm.pi Is Nothing Then
            FDAPUploadItem = False
        Else
            FDAPUploadItem = IIf(FdapProjectKeyClass.GetValue(MainForm.pi.ProjectID, "FDAPRelDataUpload").Equals("1"), True, False)


        End If
      
        If FDAPUploadItem Then

            ' Timer_FDAPUpload.Start()
            FdapUploaddataClass.Instance.Start()


        Else

            Timer_FDAPUpload.Start()
        End If

        'Timer_FDAPUpload.Stop()
        'FdapUploaddataClass.Instance.Start()


    End Sub

    Private Sub InitFDAPUpdate()

        AddHandler FdapUploaddataClass.Instance.FdapDataUploadFinishedEvent, AddressOf BeginFDAPHistoryData

    End Sub
    Private Sub BeginFDAPHistoryData(ByVal sender As Object, ByVal e As EventArgs)
        Timer_FDAPUpload.Start()
    End Sub

    Private Sub fdapdataMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles fdapdataMenuItem.Click

    End Sub

    Private Sub FDAPHisDataMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FDAPHisDataMenuItem.Click
        Dim frm As New FdapHisDataSetForm
        frm.ShowDialog()
    End Sub

    Private Sub FDAPrelDataMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FDAPrelDataMenuItem.Click
        Dim frm As New FdapRelDataSetForm
        frm.ShowDialog()
    End Sub

    Private Sub MenuOnlineCold_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuOnlineCold.Click
        ShowParameterForm(Of ColdIOParameterForm)()
    End Sub

    Private Sub MenuOfflineCold_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuOfflineCold.Click
        Dim frm As New ColdIOParameterForm(False)

        frm.ShowDialog()
    End Sub

    Private Sub MenuColdActive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuColdActive.Click
        Me.ShowParameterForm(Of ColdActiveForm)()
    End Sub

    Private Sub SetAIPortMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetAIPortMenuItem.Click
        ShowParameterForm(Of AIValueRefForm)()
    End Sub

    Private Sub VersionReadMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VersionReadMenuItem.Click
        ShowParameterForm(Of VersionReadClassForm)()

    End Sub

    Private Sub UploadSMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UploadSMenuItem.Click
        Dim frm As New ServerHDataSetForm
        frm.ShowDialog()
    End Sub

    Private Sub Timer_ServerUpload_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_ServerUpload.Tick

        Dim FDAPUploadItem As Boolean
        Timer_ServerUpload.Stop()

        If MainForm.pi Is Nothing Then

            Timer_ServerUpload.Start()
            Exit Sub

        Else

            '如果需要启动上传数据，启动历史数据上传接口线程
            FDAPUploadItem = IIf(FdapProjectKeyClass.GetValue(MainForm.pi.ProjectID, "ServerHisDataUpload").Equals("1"), True, False)

        End If


        If FDAPUploadItem Then


            ServerUploaddataClass.Instance.Start()


        Else

            Timer_ServerUpload.Start()
        End If
    End Sub

    Public Shared Function readConfig(ByVal strkey As String) As String

        Dim strreturn As String
        Dim appreader As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader()
        Try
            strreturn = appreader.GetValue(strkey, Type.GetType("System.String")).ToString()
        Catch ex As Exception
            strreturn = ex.Message.ToString()
        Finally
            appreader = Nothing
        End Try
        Return strreturn
    End Function

    Private Sub InitServerUpdate()

        AddHandler ServerUploaddataClass.Instance.ServerDataUploadFinishedEvent, AddressOf BeginServerHistoryData

    End Sub
    Private Sub BeginServerHistoryData(ByVal sender As Object, ByVal e As EventArgs)
        Timer_ServerUpload.Start()
    End Sub

    

    Private Sub LEDMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LEDMenuItem.Click
        
    End Sub

    Private Sub Timer_FDAPExDate_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_FDAPExDate.Tick

        Dim FDAPUploadItem As Boolean
        Timer_FDAPExDate.Stop()

        '如果需要启动上传数据，启动FDAP数据上传接口线程
        If _pi Is Nothing Then
            FDAPUploadItem = False
        Else
            FDAPUploadItem = IIf(FdapProjectKeyClass.GetValue(MainForm.pi.ProjectID, "FDAPHisDataUpload").Equals("1"), True, False)

        End If


        If FDAPUploadItem Then

            ' Timer_FDAPUpload.Start()
            FdapHisdataClass.Instance.Start()


        Else

            Timer_FDAPExDate.Start()
        End If

    End Sub

    Private Sub InitHisFDAPUpdate()

        AddHandler FdapHisdataClass.Instance.FdapHisDataUploadFinishedEvent, AddressOf BeginHisFDAPHistoryData

    End Sub
    Private Sub BeginHisFDAPHistoryData(ByVal sender As Object, ByVal e As EventArgs)
        Timer_FDAPExDate.Start()
    End Sub

    Private Sub mnuLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuLog.Click

    End Sub

    Private Sub NetSetMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NetSetMenuItem.Click
        ShowParameterForm(Of NetworkSetForm)()
    End Sub

    Private Sub DeviceNetWorkItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeviceNetWorkItem.Click
        ShowParameterForm(Of DeviceNetWorkForm)()
    End Sub

    Private Sub Timer_lLED_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_lLED.Tick

        Dim LEDshow As Boolean
        Timer_lLED.Stop()

        '是否启动LED显示
        If MainForm.pi Is Nothing Then
            LEDshow = False
        Else
            LEDshow = IIf(KeyValuePairClass.GetValue(MainForm.pi.ProjectID, "lLEDShowEnable").Equals("1"), True, False)


        End If

        If LEDshow Then

            lLEDUploaddataClass.Instance.Start()


        Else

            Timer_lLED.Start()
        End If

    End Sub
    Private Sub InitlLEDUpdate()

        AddHandler lLEDUploaddataClass.Instance.lLEDDataUploadFinishedEvent, AddressOf BeginlLEDHistoryData

    End Sub
    Private Sub BeginlLEDHistoryData(ByVal sender As Object, ByVal e As EventArgs)
        Timer_lLED.Start()
    End Sub

    Private Sub Timer_sLED_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_sLED.Tick

        Dim LEDshow As Boolean
        Timer_sLED.Stop()

        '是否启动LED显示
        If MainForm.pi Is Nothing Then
            LEDshow = False
        Else
            LEDshow = IIf(KeyValuePairClass.GetValue(MainForm.pi.ProjectID, "sLEDShowEnable").Equals("1"), True, False)


        End If

        If LEDshow Then

            sLEDUploaddataClass.Instance.Start()


        Else

            Timer_sLED.Start()
        End If

    End Sub

    Private Sub InitsLEDUpdate()

        AddHandler sLEDUploaddataClass.Instance.sLEDDataUploadFinishedEvent, AddressOf BeginsLEDHistoryData

    End Sub
    Private Sub BeginsLEDHistoryData(ByVal sender As Object, ByVal e As EventArgs)
        Timer_sLED.Start()
    End Sub

    Private Sub LEDShowMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LEDShowMenuItem.Click
        Dim frm As New LEDSetForm
        frm.ShowDialog()
    End Sub

    
    Private Sub SetLEDshowMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetLEDshowMenuItem.Click
        Dim frm As New SetLEDShowTimeForm
        frm.ShowDialog()
    End Sub

    Private Sub sLEDShowMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sLEDShowMenuItem.Click
        Dim frm As New sLEDSetForm
        frm.ShowDialog()
    End Sub

    Private Sub sSetLEDshowMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sSetLEDshowMenuItem.Click
        Dim frm As New SetsLEDShowTimeForm
        frm.ShowDialog()
    End Sub
End Class